#include "HeartTask.h"

HeartTask::HeartTask(char* body, int client_fd, int len, int shmid, int msgid):BaseTask(body, client_fd, len, shmid, msgid)
{
}

void HeartTask::working()
{	
	cout << "心跳bao     响应" << endl;
	char send[MEMORYSIZE] = { 0 };
	HEAD head = { 0 };
	//写头
	head.checksum = 10;
	head.data_len = 0;
	head.index = 1;
	head.service_type = HEART;
	//头体结合
	memcpy(send, &head, sizeof(HEAD));
	//寻找空闲数据快
	ShmControl* shm = (ShmControl*)shmat(shmid, NULL, 0);
	int index = -1;//空闲下标
	// 寻找下一个空闲块（状态0）
	for (int i = 0; i < MEMORYNUMBER; i++) {
		int status = shm->blocks[i].status;
		if (status == 0) { // 空闲
			index = i;
			break;
		}
	}
	//写入共享内存
	sem_p(sem_shm, 0);//获取共享内存锁
	ShmBlock* block = &shm->blocks[index];
	memcpy(block->data, send, sizeof(block->data));//考入共享内存
	block->status = 1;                   // 标记为已写
	shmdt(shm);
	sem_v(sem_shm, 0);//释放共享内存锁
	//写入消息队列
	MSG msg = { 0 };
	msg.client_fd = client_fd;
	msg.index = index;
	msg.mtype = 1;
	msgsnd(msgid, &msg, sizeof(MSG), 0);
	cout << "心跳响应" << endl;
}